package com.sdonkey.score.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sdonkey.score.bean.AdInfoBean;
import com.sdonkey.score.bean.ApplicationNewBean;
import com.sdonkey.score.bean.DeveloperBean;
import com.sdonkey.score.dao.IAdScoreManagerDao;
import com.sdonkey.score.dao.IMyAdsDao;
import com.sdonkey.score.dto.AppADsDto;
import com.sdonkey.score.dto.DeveloperAdsDto;
import com.sdonkey.score.service.IMyAdsService;
import com.sdonkey.score.util.DurationUtil;
import com.sdonkey.score.util.FormValidateUtil;
import com.sdonkey.score.util.SqlUtil;
import com.sdonkey.score.util.StaticVariable;
import org.apache.ibatis.annotations.Param;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public class MyAdsServiceImpl implements IMyAdsService {

    private Logger logger = Logger.getLogger(MyAdsServiceImpl.class);

    @Autowired
    IMyAdsDao myAdsDao;
    @Autowired
    IAdScoreManagerDao adScoreManagerDao;

    @Override
    //@Cacheable("selectDeveloper_Ads")
    public Map<String, Object> selectDeveloper_Ads(String userId, int intpage) {
        PageHelper.startPage(intpage, StaticVariable.developerAds_num);
        Page<DeveloperAdsDto> developerAdsList = (Page<DeveloperAdsDto>) myAdsDao.selectDeveloper_Ads(userId);
        for (DeveloperAdsDto developerAdsDto : developerAdsList) {
            if (developerAdsDto != null && FormValidateUtil.isNotEmpty(developerAdsDto.getAd_homepage())) {
                developerAdsDto.setAd_homepage(StaticVariable.picurladdr + developerAdsDto.getAd_homepage());
            }
            if (developerAdsDto != null && FormValidateUtil.isNotEmpty(developerAdsDto.getLogo())) {
                developerAdsDto.setLogo(StaticVariable.picurladdr + developerAdsDto.getLogo());
            }
            DeveloperAdsDto developerAds = myAdsDao.getFinishInfo(userId, developerAdsDto.getDev_id());    //已播放信息
            if (developerAds == null || FormValidateUtil.isEmpty(developerAds.getPlayfinish_video_sum())) {
                developerAdsDto.setToplay_video(DurationUtil.getToPlay_Video_Times(developerAdsDto.getDuration_sum(), "0"));
            } else {
                developerAdsDto.setToplay_video(DurationUtil.getToPlay_Video_Times(developerAdsDto.getDuration_sum(), developerAds.getPlayfinish_video_sum()));
            }
            developerAdsDto.setDuration_sum(DurationUtil.getToPlay_Video_Times(developerAdsDto.getDuration_sum(), "0"));
            if (developerAds == null || FormValidateUtil.isEmpty(developerAds.getPlayfinish_picture_sum())) {
                developerAdsDto.setPlayfinish_picture_sum("0");
            } else {
                developerAdsDto.setPlayfinish_picture_sum(developerAds.getPlayfinish_picture_sum());
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("nowpage", developerAdsList.getPageNum());
        map.put("sumpage", developerAdsList.getPages());
        map.put("developerAdsList", developerAdsList.getResult());
        return map;
    }

    @Override
    //@Cacheable("selectDeveloper_Ads")
    public Map<String, Object> selectDeveloper_Ads(String userId, String devId, String flag, int intpage) {
        if (FormValidateUtil.isEmpty(flag)) {
            flag = "v";
        }
        PageHelper.startPage(intpage, StaticVariable.developerAds_num);
        Page<DeveloperAdsDto> developerAdsList = (Page<DeveloperAdsDto>) myAdsDao.selectOneDeveloper_Ads(userId, devId, flag, intpage);
        List<String> adIds = myAdsDao.selectFinish_AdId(userId);
        for (DeveloperAdsDto developerAdsDto : developerAdsList) {
            if (developerAdsDto != null && FormValidateUtil.isNotEmpty(developerAdsDto.getAd_homepage())) {
                developerAdsDto.setAd_homepage(StaticVariable.picurladdr + developerAdsDto.getAd_homepage());
            }
            if (developerAdsDto != null && FormValidateUtil.isNotEmpty(developerAdsDto.getLogo())) {
                developerAdsDto.setLogo(StaticVariable.picurladdr + developerAdsDto.getLogo());
            }
            for (String adId : adIds) {
                if (adId.equals(developerAdsDto.getAd_id())) {
                    developerAdsDto.setFinish("1");        //添加用户播放完毕标志
                }
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("nowpage", developerAdsList.getPageNum());
        map.put("sumpage", developerAdsList.getPages());
        map.put("developerAdsList", developerAdsList.getResult());
        return map;
    }

    @Override
    //@Cacheable("selectMyAds")
    public Page<AdInfoBean> selectMyAds(Integer devId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Page<AdInfoBean> AdInfoList = (Page<AdInfoBean>) myAdsDao.selectMyAds(devId);
        for (AdInfoBean adinfo : AdInfoList) {
            if (FormValidateUtil.isNotEmpty(adinfo.getCompany_logo())) {
                adinfo.setCompany_logo(StaticVariable.picurladdr + adinfo.getCompany_logo());
            }
        }
        return AdInfoList;
    }

    @Override
    //@Cacheable("selectAd")
    public Page<AdInfoBean> selectAd(Integer adv_id, String ad_type, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Page<AdInfoBean> AdInfoList = (Page<AdInfoBean>) myAdsDao.selectAd(adv_id, ad_type);
        for (AdInfoBean adinfo : AdInfoList) {
            if (FormValidateUtil.isNotEmpty(adinfo.getAd_homepage())) {
                adinfo.setAd_homepage(StaticVariable.picurladdr + adinfo.getAd_homepage());
            }
        }
        return AdInfoList;

    }

    @Override
    //@Cacheable("selectMyCollectionAds")
    public Page<AdInfoBean> selectMyCollectionAds(String devId, String ad_type, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Page<AdInfoBean> list = (Page<AdInfoBean>) myAdsDao.selectMyCollectionAds(devId, ad_type);
        for (AdInfoBean info : list) {
            if (FormValidateUtil.isNotEmpty(info.getAd_homepage())) {
                info.setAd_homepage(StaticVariable.picurladdr + info.getAd_homepage());
            }
        }
        return list;

    }

    @Override
    //@Cacheable("selectMyDevelopers")
    public Map<String, Object> selectMyDevelopers(String userId, int intpage) {
        PageHelper.startPage(intpage, StaticVariable.myDevelopers_num);
        Page<DeveloperBean> developersList = (Page<DeveloperBean>) myAdsDao.selectMyDevelopers(userId);
        for (DeveloperBean developerBean : developersList) {
            if (developerBean != null && FormValidateUtil.isNotEmpty(developerBean.getLogo())) {
                developerBean.setLogo(StaticVariable.picurladdr + developerBean.getLogo());
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("nowpage", developersList.getPageNum());
        map.put("sumpage", developersList.getPages());
        map.put("developersList", developersList.getResult());
        return map;
    }

    @Override
    //@Cacheable("searchDevelopers")
    public Map<String, Object> searchDevelopers(String userId, String info, String first, int intpage) {
        if (intpage == 0) {
            Map<String, Object> map = new HashMap<>();
            List<DeveloperBean> list = myAdsDao.searchDevelopers(info);
            map.put("developersList", list);
            return map;
        }
        List<Integer> devIds = myAdsDao.selectMyDevIds(userId);
        Page<DeveloperBean> developersList = new Page<DeveloperBean>();
        if (FormValidateUtil.isEmpty(first)) {
            if (!FormValidateUtil.isEmpty(info)) {
                SqlUtil.replace(info);
            }
            PageHelper.startPage(intpage, StaticVariable.myDevelopers_num);
            developersList = (Page<DeveloperBean>) myAdsDao.searchDevelopers(info);
        } else {
            PageHelper.startPage(intpage, StaticVariable.myDevelopers_num);

            developersList = (Page<DeveloperBean>) myAdsDao.searchDevelopers_Fl(userId, first);
        }
        for (DeveloperBean developer : developersList) {
            for (Integer id : devIds) {
                if (developer.getId() == id) {
                    developer.setAlreadycare("1");        // 添加已关注内容商标记
                }
            }
            if (FormValidateUtil.isNotEmpty(developer.getLogo())) {
                developer.setLogo(StaticVariable.picurladdr + developer.getLogo());
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("nowpage", developersList.getPageNum());
        map.put("sumpage", developersList.getPages());
        map.put("developersList", developersList.getResult());
        return map;
    }

    @Override
    @Transactional
    //@CachePut(value={"selectMyDevelopers","searchDevelopers","selectDeveloper_Ads","selectDeveloper_Ads","selectDevelopers"})
    public int addDeveloper(String userId, String devId) {
        int flag;
        // 查询是否关注过该内容商
        Integer ifCared = myAdsDao.selectIfCaredDev(userId, devId);
        if (ifCared != null && ifCared > 0) {    // 关注过就更新状态为“1”
            flag = myAdsDao.addDeveloper_Update(ifCared);
        } else {    // 没关注过就添加一条记录 设置状态为“1”
            flag = myAdsDao.addDeveloper(userId, devId);
        }
        logger.info("用户" + userId + " 关注（添加）内容商" + devId);
        //查询用户是否已有与该内容商相对应的专项积分账户
//        Boolean status = myAdsDao.queryIfHasTowardAccount(userId, devId);
//        if (status) {
//            //更新账户状态为1
//            myAdsDao.updateTowardAccountStatus_Add(userId, devId);
//        } else {
//            //创建一个与该内容商相对应的专项积分账户(如果不存在此账户)
//            myAdsDao.createTowardAccount(userId, devId);
//        }
        return flag;
    }

    @Override
    //@CachePut(value={"selectMyDevelopers","searchDevelopers","selectDeveloper_Ads","selectDeveloper_Ads","selectDevelopers"})
    public int deleteDeveloper(String userId, String devId) {
        int i = myAdsDao.deleteDeveloper(userId, devId);
        if (i > 0) {
            //更新用户对应的该内容商的专项积分账户 状态 为-1
//            myAdsDao.updateTowardAccountStatus_Del(userId, devId);
            logger.info("用户" + userId + " 取消关注（删除）内容商" + devId);
            return 1;
        }
        return -1;
    }

    @Override
    //@Cacheable("selectDevelopers")
    public Map<String, Object> selectDevelopers(String userId, String devId, int intpage, String flag) {
        //查询内容商基本信息
        DeveloperBean developer = myAdsDao.selectDeveloperByDevid(devId);
        if (developer != null && FormValidateUtil.isNotEmpty(developer.getLogo())) {
            developer.setLogo(StaticVariable.picurladdr + developer.getLogo());
        }
        Map<String, Object> map = new HashMap<String, Object>();
        //内容商详情页面使用
        if (intpage == 0) {    //intpage=0 只查前三条
            List<ApplicationNewBean> applicationList = myAdsDao.selectApplications(devId, intpage);
            for (ApplicationNewBean applicationNewBean : applicationList) {
                if (applicationNewBean != null && FormValidateUtil.isNotEmpty(applicationNewBean.getLogourl())) {
                    applicationNewBean.setLogourl(StaticVariable.picurladdr + applicationNewBean.getLogourl());
                }
            }
            List<DeveloperAdsDto> developer_Ads_video = myAdsDao.selectOneDeveloper_Ads(null, devId, "v", intpage);
            for (DeveloperAdsDto developerAdsDto : developer_Ads_video) {
                if (developerAdsDto != null && FormValidateUtil.isNotEmpty(developerAdsDto.getAd_homepage())) {
                    developerAdsDto.setAd_homepage(StaticVariable.picurladdr + developerAdsDto.getAd_homepage());
                }
            }
            List<DeveloperAdsDto> developer_Ads_picture = myAdsDao.selectOneDeveloper_Ads(null, devId, "p", intpage);
            for (DeveloperAdsDto developerAdsDto : developer_Ads_picture) {
                if (developerAdsDto != null && FormValidateUtil.isNotEmpty(developerAdsDto.getAd_homepage())) {
                    developerAdsDto.setAd_homepage(StaticVariable.picurladdr + developerAdsDto.getAd_homepage());
                }
            }
            map.put("developer_Ads_videoList", developer_Ads_video);
            map.put("developer_Ads_pictureList", developer_Ads_picture);
            map.put("applicationList", applicationList);
        } else { //更多页面使用
            Integer num = 0, nowpage = 1, sumpage = 1;
            //查询内容商专属视频或者图片广告
            if ("v".equals(flag) || "p".equals(flag)) {
                //查询内容商专属视频或者图片广告的数量
                num = myAdsDao.select_VideoOrPictureAds_Num(devId, flag);
                //查询内容商的广告列表
                PageHelper.startPage(intpage, StaticVariable.developerAds_num);
                Page<DeveloperAdsDto> developer_Ads = (Page<DeveloperAdsDto>) myAdsDao.selectOneDeveloper_Ads(null, devId, flag, intpage);
                for (DeveloperAdsDto developerAdsDto : developer_Ads) {
                    if (developerAdsDto != null && FormValidateUtil.isNotEmpty(developerAdsDto.getAd_homepage())) {
                        developerAdsDto.setAd_homepage(StaticVariable.picurladdr + developerAdsDto.getAd_homepage());
                    }
                }
                if ("v".equals(flag)) {
                    map.put("developer_Ads_videoList", developer_Ads.getResult());
                } else if ("p".equals(flag)) {
                    map.put("developer_Ads_pictureList", developer_Ads.getResult());
                }
                //获取分页后分页信息
                nowpage = developer_Ads.getPageNum();
                sumpage = developer_Ads.getPages();
            }
            //查询内容商应用
            if ("a".equals(flag)) {
                //查询内容商应用的数量
                num = myAdsDao.select_App_Num(devId);
                //查询内容商应用的列表
                PageHelper.startPage(intpage, StaticVariable.developerAds_num);
                Page<ApplicationNewBean> applicationList = (Page<ApplicationNewBean>) myAdsDao.selectApplications(devId, intpage);
                for (ApplicationNewBean applicationNewBean : applicationList) {
                    if (applicationNewBean != null && FormValidateUtil.isNotEmpty(applicationNewBean.getLogourl())) {
                        applicationNewBean.setLogourl(StaticVariable.picurladdr + applicationNewBean.getLogourl());
                    }
                }
                //获取分页后分页信息
                nowpage = applicationList.getPageNum();
                sumpage = applicationList.getPages();
                map.put("applicationList", applicationList.getResult());
            }
            map.put("nowpage", nowpage);
            map.put("sumpage", sumpage);
            developer.setNum(num);
        }
        //判断是否关注此内容商
        if (myAdsDao.selectIfCareingDev(userId, devId) != null && myAdsDao.selectIfCareingDev(userId, devId) > 0) {
            developer.setAlreadycare("1");
        }
        map.put("developer", developer);
        return map;
    }

    @Override
    //@Cacheable("getUserAppList")
    public Map<String, Object> getUserAppList(String userId, int page, String status) {
        PageHelper.startPage(page, StaticVariable.page_appAd_num);
        Page<AppADsDto> list = (Page<AppADsDto>) myAdsDao.getUserAppList(userId, status);
        List<AppADsDto> result = list.getResult();
        for (AppADsDto app : result) {
            app.setApp_logourl(StaticVariable.picurladdr + app.getApp_logourl());
        }
        Map<String, Object> map = new HashMap<>();
        map.put("appList", result);
        map.put("nowpage", list.getPageNum());
        map.put("sumpage", list.getPages());
        return map;
    }

    @Override
    //@Cacheable("selectAppByCondition")
    public Map<String, Object> selectAppByCondition(String userId, String condition, int page) {
        PageHelper.startPage(page, StaticVariable.page_app_num);
        Page<ApplicationNewBean> list = (Page<ApplicationNewBean>) myAdsDao.selectAppByCondition(condition);
        Map<String, Object> map = new HashMap<>();
        if (list.getResult() != null) {
            List<ApplicationNewBean> result = list.getResult();
            List<String> ids = myAdsDao.selectAddedAppId(userId);
            for (ApplicationNewBean app : result) {
                for (String id : ids) {
                    if (app.getId().toString().equals(id)) {
                        app.setCared("1");
                    }
                }
                app.setLogourl(StaticVariable.picurladdr + app.getLogourl());
            }
            map.put("appList", result);
        }
        map.put("nowpage", list.getPageNum());
        map.put("sumpage", list.getPages());
        return map;
    }

    @Override
    @Transactional
    //@CachePut(value={"selectMyDevelopers","searchDevelopers","selectDeveloper_Ads","selectDeveloper_Ads","selectDevelopers"})
    public int bindAppAccount(String userId, String app_id, String account) {
        int status = -1;
        try {
            if (!myAdsDao.ifHasTowardAccount(userId, app_id)) {
                Double m = adScoreManagerDao.getPriceBuyAppId(app_id);
                if (m == null) {
                    m = 0.00;
                }
                String money = m.toString();
                if (myAdsDao.createTowardAccount(userId, app_id) > 0) {//创建专项积分账户
                    status = myAdsDao.bindAppAccount(userId, app_id, account, money);
                    if (money.equals("0.00") || money.equals("0.0") || money.equals("0")) {
                        //todo 应用服务充值或生效
                    }
                    logger.info("用户" + userId + " 绑定应用" + app_id + " 帐号" + account);
                }
            } else {
                status = -2;
            }
        } catch (Exception e) {
            logger.error("用户" + userId + " 绑定应用" + app_id + " 帐号" + account + " 失败", e);
        }
        return status;
    }

    @Override
    //@Cacheable("selectOneAppAds")
    public Map<String, Object> selectOneAppAds(String userId, String app_id, String ad_type, int page) {
        PageHelper.startPage(page, StaticVariable.page_oneappAd_num);
        Page<AppADsDto> list = (Page<AppADsDto>) myAdsDao.selectOneAppAds(app_id, ad_type);
        List<String> adIds = myAdsDao.selectFinish_AppAdId(userId, app_id);
        for (AppADsDto appADsDto : list) {
            if (appADsDto != null && FormValidateUtil.isNotEmpty(appADsDto.getAd_homepage())) {
                appADsDto.setAd_homepage(StaticVariable.picurladdr + appADsDto.getAd_homepage());
            }
            if (appADsDto != null && FormValidateUtil.isNotEmpty(appADsDto.getApp_logourl())) {
                appADsDto.setApp_logourl(StaticVariable.picurladdr + appADsDto.getApp_logourl());
            }
            for (String adId : adIds) {
                if (adId.equals(appADsDto.getAd_id())) {
                    appADsDto.setFinish("1");        //添加用户播放完毕标志
                }
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("nowpage", list.getPageNum());
        map.put("sumpage", list.getPages());
        map.put("appAdsList", list.getResult());
        return map;
    }


}
